package com.tiancikeji.zaoke.app.util;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class PayUtil {

    private static Log logger = LogFactory.getLog(PayUtil.class);

    public static final String SUBJECT_RECHARGE = "糯米网充值";

    public static Map<String, String> PAY_TYPE_ADAPTER = new ConcurrentHashMap<String, String>();

    public static List<String> FORBIDDEN_WORDS = new ArrayList<String>();
    public static final String FORBIDDEN_WORD_SUB = "糯米网商品";
    public static boolean USE_CHINA_MOBILE_BANK = true;
    public static Set<String> CHINA_MOBILE_BANK_LIST = new HashSet<String>();

    public static final int CHINA_MOBILE_BANK_STATUS_ON = 1;

    public static void switchUseChinaMobileBank() {
        USE_CHINA_MOBILE_BANK = !USE_CHINA_MOBILE_BANK;
    }

    public static void setChinaMobileBankStatus(int status) {
        if (status == CHINA_MOBILE_BANK_STATUS_ON) {
            USE_CHINA_MOBILE_BANK = true;
        } else {
            USE_CHINA_MOBILE_BANK = false;
        }
    }

    public static final String[] WEBBANK_PAYTYPE = new String[]{};
    static {
        PAY_TYPE_ADAPTER.clear();
        CHINA_MOBILE_BANK_LIST.add("SPDB"); //浦发
        CHINA_MOBILE_BANK_LIST.add("BCOM"); //交通银行
        CHINA_MOBILE_BANK_LIST.add("ICBC"); //工商银行

    }

    public static String encodeURLComponent(String raw) {
        try {
            return URLEncoder.encode(raw, "utf-8");
        } catch (UnsupportedEncodingException e) {
            return raw;
        }
    }

    /**
     * 拼凑属性的url参数串
     *
     * @param params
     * @param encoding
     * @return
     */
    public static String encodeParam(Map<String, String> params, String encoding) {
        if (params == null || params.size() <= 0) {
            return null;
        }

        StringBuffer paramBuffer = new StringBuffer();
        boolean firstParamReady = false;
        for (Map.Entry<String, String> param : params.entrySet()) {
            if (firstParamReady == true) {
                paramBuffer.append("&");
            }

            String paramStr = getParamStr(param.getKey(), param.getValue(), encoding);
            if (paramStr != null) {
                paramBuffer.append(paramStr);
            }

            firstParamReady = true;
        }

        if (paramBuffer.length() > 0) {
            return paramBuffer.toString();
        } else {
            return null;
        }
    }

    /**
     * 根据字符编码拼凑某一属性的url参数串
     *
     * @param paramName
     * @param paramValue
     * @param paramValueEncoding
     * @return
     */
    public static String getParamStr(String paramName, String paramValue, String paramValueEncoding) {
        StringBuffer paramBuffer = new StringBuffer();
        try {
            paramBuffer.append(paramName);
            paramBuffer.append("=");

            // TODO
            // 拉卡拉回调接口会间接使用此函数，暂时将“partner_extendinfo”硬编码在此，后续修改
            if (paramName != null && paramName.equals("partner_extendinfo")) {
                paramBuffer.append(paramValue);
            } else {
                paramBuffer.append(URLEncoder.encode(paramValue, paramValueEncoding));
            }

            return paramBuffer.toString();
        } catch (UnsupportedEncodingException e) {
            logger.error("参数名：" + paramName + "参数值：" + paramValue, e);
            return null;
        }

    }

    /**
     * 使用UTF-8编码拼凑某一属性的url参数串
     *
     * @param paramName
     * @param paramValue
     * @return
     */
    public static String getParamStr(String paramName, String paramValue) {
        return getParamStr(paramName, paramValue, "UTF-8");
    }

    /**
     * 将Map的值由数组格式转换为字符串格式（各数组元素由逗号连接）
     *
     * @param input
     * @return
     */
    public static Map<String, String> trans(Map<String, String[]> input) {
        if (input == null) {
            return null;
        }

        Map<String, String> map = new HashMap<String, String>();
        for (Map.Entry<String, String[]> entry : input.entrySet()) {
            String key = entry.getKey();
            String[] value = entry.getValue();
            String valueStr = trans(value);
            map.put(key, valueStr);
        }

        return map;

    }

    /**
     * 将数组值拼成字符串，以逗号连接
     *
     * @param value
     * @return
     */
    public static String trans(String[] value) {
        if (value == null) {
            return null;
        }

        StringBuffer buffer = new StringBuffer();
        for (int i = 0; i < value.length; i++) {
            if (i != 0) {
                buffer.append(",");
            }
            buffer.append(value[i]);
        }

        if (buffer.length() > 0) {
            return buffer.toString();
        } else {
            return null;
        }
    }

    /**
     * 将map中的null值转换为空字符串
     *
     * @param input
     */
    public static void null2EmptyStr(Map<String, String> input) {
        if (input == null) {
            return;
        }

        for (Map.Entry<String, String> entry : input.entrySet()) {
            String key = entry.getKey();
            String value = entry.getValue();
            value = null2EmptyStr(value);
            input.put(key, value);
        }

    }

    /**
     * 将null值转换为空字符串
     *
     * @param input
     * @return
     */
    public static String null2EmptyStr(String input) {
        return (input == null) ? "" : input;
    }


    public static Map<String, String> getParaMap(String paraStr) {
        Map<String, String> retParamMap = new HashMap<String, String>();
        String[] retParamArr = paraStr.split("&");
        for (String entry : retParamArr) {
            String[] keyAndValue = entry.split("=");
            retParamMap.put(keyAndValue[0], keyAndValue[1]);
        }
        return retParamMap;
    }

    public static String mapToStr(TreeMap<String, String> paras) {
        StringBuffer bf = new StringBuffer();
        for (Map.Entry<String, String> entry : paras.entrySet()) {
            String key = entry.getKey().toString();
            String value = entry.getValue().toString();

            if (value == null || "".equals(value)) {
                continue;
            }
            bf.append(key).append("=").append(value).append("&");
        }

        return bf.toString();
    }


    /**
     * 元转分
     *
     * @param amount
     * @return
     */
    public static long changeY2F(String amount) {
        String currency = amount.replaceAll("\\$|\\￥|\\,", "");  //处理包含, ￥ 或者$的金额
        int index = currency.indexOf(".");
        int length = currency.length();
        Long amLong = 0l;
        if (index == -1) {
            amLong = Long.valueOf(currency + "00");
        } else if (length - index >= 3) {
            amLong = Long.valueOf((currency.substring(0, index + 3)).replace(".", ""));
        } else if (length - index == 2) {
            amLong = Long.valueOf((currency.substring(0, index + 2)).replace(".", "") + 0);
        } else {
            amLong = Long.valueOf((currency.substring(0, index + 1)).replace(".", "") + "00");
        }
        return amLong;
    }

    /**
     * 元转分
     *
     * @param amount
     * @return
     */
    public static String changeY2FStr(String amount) {

        return String.valueOf(changeY2F(amount));
    }

}
